﻿

using IotContract.Interfaces.Process;
using F29ServerProcess.Models;
using XT.Common.Services;
using F29ServerProcess.Interfaces;

namespace F29ServerProcess;
public class ServerMainProcess: IServerMainProcess
{
    private IEnumerable<IServerProcessHandle> _processes;
    private ILogService _logService;
    private CancellationTokenSource _cancellationTokenSource;
    private IProcessDataService _processDataService;
    public ServerMainProcess(IEnumerable<IServerProcessHandle> handles,ILogService logService,IProcessDataService processDataService)
    {
        _processes= handles.Where(x=>x.ProcessName==ProcessName);
        _logService = logService;
        _processDataService = processDataService;
    }
    public string ProcessName { get; set; } = F29ServerConst.ProcessName;

    public async Task<bool> Run()
    {
        _logService.Log($"{ProcessName} Dll Begin Run");

        await _processDataService.IniData();

        _cancellationTokenSource?.Cancel();

        await Task.Delay(1000);

        _cancellationTokenSource = new CancellationTokenSource();


        foreach (var process in _processes)
        {
            Task.Factory.StartNew(async(o) =>
            {
                if(o is IServerProcessHandle handle)
                {
                    while (true)
                    {
                        if (_cancellationTokenSource.IsCancellationRequested)
                        {
                            handle.Stop();
                            break;
                        }
                        await handle.ParsingData();
                        await handle.ProcessData();
                        await handle.ProcessOrder();
                        await handle.ProcessWarn();

                        await Task.Delay(200);
                    }
                    
                }
            },process,_cancellationTokenSource.Token,TaskCreationOptions.LongRunning,TaskScheduler.Default);        
        }


      
        return true;
    }

    public async Task<bool> Stop()
    {
        _cancellationTokenSource?.Cancel();
        
        _logService.Log($"{ProcessName} Dll Stop");
        return true;
    }
}
